<template>
  <div class="chat-container">
    <!-- 左侧消息区 -->
    <div class="chat-messages" ref="messagesContainer">
      <div v-for="(msg, index) in messages" :key="index" class="chat-message">
        <b>{{ msg.fromUser?.userName || msg.from }}:</b>
        {{ msg.content }}
      </div>
    </div>

    <!-- 右侧用户信息 + 输入区 -->
    <div class="chat-side-panel">
      <!-- 用户信息 -->
      <div class="user-info" v-if="userInfo">
        <img :src="userInfo.avatar || defaultAvatar" class="avatar" />
        <p><b>{{ userInfo.userName }}</b></p>
        <p>角色: {{ userInfo.role }}</p>
      </div>

      <!-- 输入区 -->
      <div class="chat-input-panel">
        <textarea
          v-model="message"
          placeholder="输入消息..."
          @keyup.enter="sendMessage"
          class="input message"
        ></textarea>

        <button :disabled="!connected" @click="sendMessage" class="send-btn">
          {{ connected ? "发送" : "连接中..." }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import SockJS from "sockjs-client/dist/sockjs.min.js";
import Stomp from "stompjs";
import { getUsers } from "../api/user"; // 假设后端有 /user/info 接口

window.global = window;

const messages = ref([]);
const message = ref("");
const connected = ref(false);
const messagesContainer = ref(null);

const userInfo = ref(null);
const defaultAvatar = "/default-avatar.png"; // 默认头像

let stompClient = null;

onMounted(async () => {
  // 获取当前登录用户信息
  try {
    const res = await getUsers();
    if (res.code === 200) {
      userInfo.value = res.data;
    }
  } catch (e) {
    console.error("获取用户信息失败", e);
  }

  connect();
});

function connect() {
  const socket = new SockJS("http://localhost:8888/ws-chat");
  stompClient = Stomp.over(socket);

  stompClient.connect(
    {},
    () => {
      connected.value = true;

      stompClient.subscribe("/topic/messages", (msg) => {
        try {
          const data = JSON.parse(msg.body);
          messages.value.push(data);

          nextTick(() => {
            if (messagesContainer.value) {
              messagesContainer.value.scrollTop =
                messagesContainer.value.scrollHeight;
            }
          });
        } catch (e) {
          console.error("消息解析失败:", msg.body);
        }
      });
    },
    (err) => {
      connected.value = false;
      console.error("连接失败:", err);
    }
  );
}

function sendMessage() {
  if (message.value.trim() && stompClient && connected.value && userInfo.value) {
    stompClient.send(
      "/app/sendMessage",
      {},
      JSON.stringify({
        from: userInfo.value.userName,
        fromUser: userInfo.value, // 附带完整用户信息
        content: message.value,
      })
    );
    message.value = "";
  }
}
</script>

<style>
.chat-container {
  display: flex;
  width: 900px;
  height: 500px;
  margin: 30px auto;
  border: 1px solid #ccc;
  border-radius: 10px;
  font-family: Arial, sans-serif;
  overflow: hidden;
}

/* 左侧消息区 */
.chat-messages {
  flex: 2;
  padding: 15px;
  border-right: 1px solid #ddd;
  overflow-y: auto;
  background: #fafafa;
}

.chat-message {
  margin-bottom: 10px;
  padding: 8px;
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

/* 右侧用户信息 + 输入区 */
.chat-side-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 15px;
  background: #fdfdfd;
}

.user-info {
  text-align: center;
  margin-bottom: 20px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-bottom: 10px;
}

.chat-input-panel {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.message {
  flex: 1;
  resize: none;
  margin-bottom: 10px;
  padding: 8px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 6px;
}

.send-btn {
  padding: 10px;
  font-size: 16px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.2s;
}

.send-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.send-btn:hover:not(:disabled) {
  background: #36976d;
}
</style>
